package CyclicBarrier_6;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class 基本用法_多线程同步点 {
    public static void main(String[] args) {
        final int THREAD_COUNT = 5;
        final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT, new Runnable() {
            public void run() {
                System.out.println("所有线程已到达屏障点，执行屏障操作");
            }
        });

        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        System.out.println("线程-" + threadId + " 开始第一阶段工作");
                        Thread.sleep((long)(Math.random() * 1000));
                        System.out.println("线程-" + threadId + " 完成第一阶段，等待其他线程");
                        barrier.await();

                        System.out.println("线程-" + threadId + " 开始第二阶段工作");
                        Thread.sleep((long)(Math.random() * 800));
                        System.out.println("线程-" + threadId + " 完成第二阶段，等待其他线程");
                        barrier.await();

                        System.out.println("线程-" + threadId + " 全部工作完成");
                    } catch (InterruptedException | BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}